import { defineStore } from 'pinia'
import { ref, onMounted } from 'vue'
import { useMemberCardStore } from './memberCard'

export const useConsumptionRecordStore = defineStore('consumptionRecord',() => {
    const memberCardStore = useMemberCardStore()

    const consumptionRecords = ref([
        {
            id: 1,
            memberId: 1,
            memberCardId: 1,
            memberCardName: '',
            operationTime: '2022-01-01 14:46:00',
            consumeTimes: 0,
            remainingTimes: 57,
            consumeAmount: 1,
            operationType: "绑卡操作",
            operator: "张老师",
            remark: "办卡的费用"
        }
    ])

    const chargeData = {
        7 : 100
    }

    const getConsumptionRecordsByMemberId = (memberId) => {
        return consumptionRecords.value.filter(record => record.memberId === memberId)
    }

    const addRecord = (record) => {
        const memberCard = memberCardStore.getMemberCardById(record.memberCardId)
        consumptionRecords.value.push({
            id: consumptionRecords.value.length + 1,
            memberId: record.memberId,
            memberCardId: record.memberCardId,
            memberCardName: memberCard.memberCardName,
            operationTime: formatDateTime(new Date()),
            consumeTimes: record.consumeTimes,
            remainingTimes: record.remainingTimes,
            consumeAmount: record.consumeAmount,
            operationType: record.operationType,
            operator: record.operator,
            remark: record.remark
        })
        const day = new Date().getDate()
        chargeData[day] = (chargeData[day] || 0) + record.consumeAmount
    }

    const getChargeData = () => {
        const res = []
        for (let i = 1; i <= new Date().getDate(); i++){
            res.push(chargeData[i] || 0)
        }
        return res
    }

    const formatDateTime = (date) => {
        var year = date.getFullYear();
        var month = (1 + date.getMonth()).toString().padStart(2, '0');
        var day = date.getDate().toString().padStart(2, '0');
        var hours = date.getHours().toString().padStart(2, '0');
        var minutes = date.getMinutes().toString().padStart(2, '0');
        var seconds = date.getSeconds().toString().padStart(2, '0');
        return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
    }

    return{
        consumptionRecords,
        getConsumptionRecordsByMemberId,
        getChargeData,
        addRecord
    }
})
